import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { STComponent, STColumn, STChange, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFSchema, SFDateWidgetSchema, SFTextWidgetSchema } from '@delon/form';
import { NzModalService } from 'ng-zorro-antd/modal';
import { TicketService } from '../../../services/ticket.service';
import { RequestedDetailComponent } from '../requested-detail/requested-detail.component';

@Component({
  selector: 'app-invoice-requested-detail',
  templateUrl: './invoice-requested-detail.component.html',
  styleUrls: ['./invoice-requested-detail.component.less', '../../../../commom/less/expend-but.less', '../../../../commom/less/box.less']
})
export class InvoiceRequestedDetailComponent implements OnInit {
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  columns: STColumn[] = this.initST();
  searchSchema: SFSchema = this.initSF();

  detail: any = {};

  selectedRows: any[] = [];
  totalCallNo = '0';
  _$expand = false;

  id = null;
  sts = null;
  headerInfo: any = {};
  constructor(
    public service: TicketService,
    private nzModalService: NzModalService,
    private route: ActivatedRoute,
    private router: Router
  ) {
    this.id = route.snapshot.params.id;
    this.sts = route.snapshot.queryParams.sts;
    this.loadHeadInfo();
  }

  ngOnInit(): void {}

  loadHeadInfo() {
    this.service.request(this.service.$api_get_invoice_requested_header_detail, { id: this.id }).subscribe(res => {
      if (res) {
        this.headerInfo = res;
      }
    });
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    this.totalCallNo = '0';
    this.selectedRows = [];
    Object.assign(requestOptions.body, { vatappHId: this.id });
    if (this.sf) {
      Object.assign(requestOptions.body, { ...this.sf?.value });
    }
    return requestOptions;
  };

  afterRes = (data: any[], rawData?: any) => {
    // this.totalCallNo = data.reduce((total, cv) => total + cv.billkpmoney, 0).toFixed(2);
    return data.map(item => ({
      ...item
    }));
  };

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        if (this.selectedRows?.length > 0) {
          this.totalCallNo = this.selectedRows.reduce((total, cv) => total + cv.billkpmoney, 0).toFixed(2);
        } else {
          this.totalCallNo = this.st._data.reduce((total, cv) => total + cv.billkpmoney, 0).toFixed(2);
        }
        break;
      case 'filter':
        this.st.load();
        break;
    }
  }

  openRequestedModal(status: any) {
    if (status === '2' && this.selectedRows.length == 0) {
      this.service.msgSrv.warning('请选择订单！');
      return;
    }
    let rows: any[] = [];
    if (status === '1') {
      rows = this.st._data.map(item => {
        const rs = Object.assign({}, { ...item });
        delete rs._values;
        return rs;
      });
    } else {
      rows = [...this.selectedRows];
    }
    const modal = this.nzModalService.create({
      nzTitle: '开票',
      nzContent: RequestedDetailComponent,
      nzWidth: 800,
      nzComponentParams: {
        i: rows,
        status: status,
        Id: this.id
      },
      nzFooter: [
        {
          type: 'default',
          label: '手工处理',
          onClick: () => {
            const params = {
              ficoVatappBillVOList: rows,
              id: this.id
            };
            this.service.request(this.service.$api_get_applyFicoVatinv, params).subscribe((res: any) => {
              if (res) {
                this.loadHeadInfo();
                this.st.load(1);
                this.service.msgSrv.success('提交成功');
                modal.destroy();
              }
            });
          }
        },
        {
          type: 'primary',
          label: '自动开票',
          onClick: () => {
            const params = {
              ficoVatappBillVOList: rows,
              id: this.id
            };
            this.service.request(this.service.$api_get_applyFicoVatinv, params).subscribe((res: any) => {
              if (res) {
                this.loadHeadInfo();
                this.st.load(1);
                this.service.msgSrv.success('提交成功');
                modal.destroy();
              }
            });
          }
        }
      ]
    });
  }

  /**
   * 移除订单
   * @returns
   */
  removeOrder() {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择订单');
      return;
    }
    this.nzModalService.warning({
      nzTitle: '确定从当前批次中移除所选订单？',
      nzContent: '移除后相关订单可以重新提交开票申请',
      nzOnOk: () => {
        const ids = this.selectedRows.map(order => order.billHId);
        this.service.request(this.service.$api_remove_bill, ids).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('移除成功');
            this.loadHeadInfo();
            this.st.reload();
          }
        });
      }
    });
  }

  goBack() {
    history.go(-1);
  }

  routeToOrder(item: any) {
    if (item.billType === '1') {
      this.router.navigate(['/order-management/vehicle/vehicle-detail/' + item.billHId]);
    } else if (item.billType === '2'){
      this.router.navigate(['/order-management/bulk/bulk-detail/' + item.billHId]);
    } else if (item.billType === '3'){
      this.router.navigate(['/order-management/vehicle/vehicle-detail/' + item.billHId]);
    }
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this._$expand = false;
  }

  /**
   * 伸缩查询条件
   */
  expandToggle() {
    this._$expand = !this._$expand;
    this.sf?.setValue('/expand', this._$expand);
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        billHCode: {
          type: 'string',
          title: '订单号',
          ui: {
            placeholder: '请输入'
          }
        },
        vatappSts: {
          type: 'string',
          title: '开票状态',
          enum: [
            { label: '全部', value: '' },
            { label: '待受理', value: '待受理' },
            { label: '待开票', value: '待开票' },
            { label: '开票中', value: '开票中' },
            { label: '已开票', value: '已开票' },
            { label: '已撤销', value: '已撤销' },
            { label: '已拒绝', value: '已拒绝' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          },
          default: ''
        },
        vatinvcode: {
          type: 'string',
          title: '发票号码',
          ui: {
            placeholder: '请输入'
          }
        },
        billType: {
          type: 'string',
          title: '订单类型',
          enum: [
            { label: '全部', value: '' },
            { label: '整车', value: '1' },
            { label: '大宗', value: '2' },
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        },
        driverinfo: {
          type: 'string',
          title: '承运司机',
          ui: {
            placeholder: '请输入',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        drivercarinfo: {
          type: 'string',
          title: '车牌号',
          ui: {
            placeholder: '请输入',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        projectId: {
          title: '所属项目',
          type: 'string',
          default: '',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => this.service.getProjectList({ projectName: q, enterpriseId: this.headerInfo?.shipperId }),
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '', index: 'key', type: 'checkbox' },
      { title: '订单号', render: 'billHCode', width: 170 },
      { title: '订单完成日期', index: 'billfinTime', type: 'date', width: 150 },
      { title: '开票状态', index: 'vatappStsLabel', width: 100 },
      { title: '所属项目', index: 'projectIdName', width: 140 },
      { title: '订单类型', index: 'billTypeLabel', width: 100,},
      { title: '装货地', index: 'loadingfrom', width: 220 },
      { title: '卸货地', index: 'loadingto', width: 220 },
      { title: '货物信息', index: 'goodsinfo', width: 150 },
      { title: '承运司机', index: 'driverinfo', width: 140 },
      {
        title: '申请金额',
        index: 'billkpmoney',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.billkpmoney }) }
      },
      {
        title: '运输费',
        index: 'fjfmoney2',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.fjfmoney2 }) }
      },
      {
        title: '附加费',
        index: 'fjfmoney',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.fjfmoney }) }
      },
      {
        title: '开票金额',
        index: 'billkpmoney',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.billkpmoney }) }
      },
      {
        title: '税率',
        index: 'billvatrate',
        width: 90,
        format: item => `9.00%`
        // bugfix 6976
        // format: item => `${item.billvatrate ? ((item.billvatrate as number) * 100).toFixed(2) : 0}%`
      },
      { title: '发票号码', index: 'vatinvcode', width: 100 },
      { title: '开票日期', index: 'vatinvtime', type: 'date', width: 150 }
    ];
  }
}
